package com.example.login;

import com.example.filter.JwtAuthenticationTokenFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 禁用 CSRF（仅示例，生产按需开启并配合 CSRF Token）
                .csrf(csrf -> csrf.disable())
                // 会话策略：前后端分离常用无状态
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))

                // 授权规则（新 DSL：authorizeHttpRequests + requestMatchers）
                .authorizeHttpRequests(authz -> authz
                        .requestMatchers("/public/**", "/login").permitAll()   // 放行
                        .anyRequest().authenticated()                        // 其余需认证
                )

                // 如需表单登录（浏览器场景），可启用并自定义
                // .formLogin(form -> form
                //     .loginPage("/login")
                //     .defaultSuccessUrl("/home")
                //     .permitAll()
                // )

                // 如需 HTTP Basic（接口场景常用）
                .httpBasic(basic -> basic.realmName("demo"));

        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // 3) 可选：完全忽略某些静态资源（不走过滤器链）
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers(
                "/css/**", "/js/**", "/images/**", "/webjars/**", "/favicon.ico"
        );
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager(); // 暴露全局 AuthenticationManager
    }
}
